package chapter4.dao;

import org.hibernate.HibernateException;

import entity.Email;
import entity.Messages;

import learnning.dao.base.HibernateDao;

public class Chapter4Dao extends HibernateDao {
	public long add(String email, String message) {
		long id = 0;
		try {
			begin();
			Email email2 = new Email(email);
			Messages messages = new Messages(message);
			messages.setEmail(email2);
			email2.setMessages(messages);
			getSession().save(email2);
			getSession().save(messages);
			System.out.println("---store ---");
			System.out.println(messages.getEmail());
			System.out.println(email2.getMessages());
			System.out.println("------------------");
			id = (Long) getSession().getIdentifier(messages);
			commit();
		} catch (HibernateException e) {
			rollback();
			e.printStackTrace();
		}
		return id;
	}

	public Messages getMessage(long id) {
		Messages messages = null;
		try {
			begin();
			messages = (Messages) getSession().get(Messages.class, id);
			System.out.println("---- get data ---");
			System.out.println(messages.getEmail());
			Email email = (Email) getSession().get(Email.class, id);
			System.out.println(email.getMessages());
			System.out.println("--------------");
			commit();
		} catch (HibernateException e) {
			rollback();
			e.printStackTrace();
		}
		return messages;
	}

}
